import { defineStore } from 'pinia'
import request from '@/utils/request'
import { topCategory } from '../constants'
import { CateItem, ApiRes, TopCategory, SubCategory } from '@/types/data'

// 处理默认项 => 因为类型为 数组包对象的数组 因此需要二次处理
const defaultCate = topCategory.map((item) => ({ name: item }))

const useCategoryStore = defineStore('category', {
  state() {
    return {
      cateList: defaultCate as CateItem[],
      topCategory: {} as TopCategory,
      subCategory: {} as SubCategory
    }
  },
  getters: {},
  actions: {
    // 获取响应的数据列表
    async getCateList() {
      const res = await request.get<ApiRes<CateItem[]>>('/home/category/head')
      // 在获取到数据之后 给每一项添加一个show字段
      res.data.result.forEach((item) => (item.show = false))
      this.cateList = res.data.result
    },

    // 控制类名显示
    show(id: string) {
      this.cateList.find((item) => item.id === id)!.show = true
    },

    // 控制类名隐藏
    hide(id: string) {
      this.cateList.find((item) => item.id === id)!.show = false
    },

    // 获取一级分类
    async getTopCategory(id: string) {
      const res = await request.get<ApiRes<TopCategory>>('/category', {
        params: { id }
      })
      this.topCategory = res.data.result
    },

    // 获取二级分类
    async getSubCategory(id: string) {
      const res = await request.get<ApiRes<SubCategory>>(`/category/sub/filter?id=${id}`)
      this.subCategory = res.data.result
    }
  }
})

export default useCategoryStore
